import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:steam_app/config/app_routes.dart';
import 'package:steam_app/config/app_theme.dart';
import 'package:steam_app/data/user_repository.dart';

import '../../provider/user_provider.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final UserRepository userRepository = UserRepository();

  String _errorText = '';

  void _login() async {
    final account = _accountController.text.trim();
    final password = _passwordController.text;

    final userProvider = context.read<UserProvider>();
    final success = await userProvider.login(account, password);

    if (success) {
      Navigator.pushReplacementNamed(context, home_page);
    } else {
      setState(() => _errorText = userProvider.errorMessage ?? '登录失败');
    }
  }

  void _navigateToRegister() {
    Navigator.pushNamed(context, register_page);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: pageBackgroundColor,
      body: Padding(
        padding: const EdgeInsets.all(32.0),
        child: Center(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(steam_logo, height: 80),
              const SizedBox(height: 40),
              _buildInputField('账号', _accountController),
              const SizedBox(height: 16),
              _buildInputField('密码', _passwordController, obscure: true),
              const SizedBox(height: 16),
              if (_errorText.isNotEmpty)
                Text(_errorText, style: const TextStyle(color: errorColor)),
              const SizedBox(height: 20),
              _buildSteamButton('登录', _login),
              const SizedBox(height: 12),
              TextButton(
                onPressed: _navigateToRegister,
                child: const Text('注册新账号', style: TextStyle(color: textColor)),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInputField(String label, TextEditingController controller, {bool obscure = false}) {
    return TextField(
      controller: controller,
      obscureText: obscure,
      style: const TextStyle(color: textColor),
      decoration: InputDecoration(
        labelText: label,
        labelStyle: const TextStyle(color: textColor),
        filled: true,
        fillColor: pageBackgroundColor,
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(borderRadiusSize)),
      ),
    );
  }

  Widget _buildSteamButton(String text, VoidCallback onPressed) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ElevatedButton.styleFrom(
        backgroundColor: greenButtonColor,
        foregroundColor: textColor,
        padding: const EdgeInsets.symmetric(horizontal: 60, vertical: 14),
        textStyle: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(borderRadiusSize)),
      ),
      child: Text(text),
    );
  }
}
